<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>6.reduce重写</title>
</head>

<body>
  <script>

    // 原生reduce 归并
    var arr = [1, 2, 3]
    var obj = {}

    var res = arr.reduce(function(prev, item, i, arr) {
      console.log(prev, item, i, arr);
      return prev + item
    }, '')
    console.log(res);

    Array.prototype.myReduce = function(fn, prev) {
      var arr = this,
          i = 1
      
      if (typeof fn !== 'function') {
        throw new Error('第一个参数必须是函数')
      }

      if (typeof prev === 'undefined') {
        prev = arr[0]
        i = 1
        for (var i = 1;i<arr.length;i++) {
          prev = fn(prev, arr[i], i, arr)
        }
      } else {
        for (var i = 0;i<arr.length;i++) {
          prev = fn(prev, arr[i], i, arr)
        }
      }

      return prev
    }

    var res1 = arr.myReduce(function(prev, item, i, arr) {
      console.log(prev, item, i, arr);
      return prev + item
    })
    console.log(res1);


  </script>
</body>

</html>